<script setup lang="ts">
import { useRouterPush } from '@/composables';
import { useAuthStore } from '@/store';
// import { useGetAuthInfo } from '@/hooks';
import { SUCCESS_MSG_DURATION } from '@/constants';
import { storeToRefs } from 'pinia';
import { ref, onMounted, computed } from 'vue';
import { showToast, showLoading, hideLoading } from '@tarojs/taro';
import { useNurseUser } from '@/service';
import Taro from '@tarojs/taro';
// import BasicMap from '@/components/basic-map/index.vue';

definePageConfig({
    navigationBarTitleText: '居家护理地址'
});

const authStore = useAuthStore();
const { nurseUser } = storeToRefs(authStore);

const { deleteHomeAddr, listHomeAddr, setDefaultHomeAddr } = useNurseUser();

const { toAddr } = useRouterPush();

const dataOptions = {
    id: 'id',
    addressName: 'name',
    phone: 'phone',
    defaultAddress: 'isDefault',
    fullAddress: 'fullAddress'
};

const visible_delete = ref(false);
const loading = ref(false);
const isDeleting = ref(false);


const _id = ref<string>('');

// 获取地址列表
async function getHomeAddrList() {
    if (isDeleting.value) {
        return;
    }

    loading.value = true;
    showLoading({ title: '加载中...' });

    try {
        const { error, success } = await listHomeAddr(nurseUser.value.id);

        if (!error && success) {
            // 检查返回的数据结构
            let addressList: NurseUser.NurseUserHomeAddr[] = [];

            if ((success as any).records && Array.isArray((success as any).records)) {
                // 分页数据结构
                addressList = (success as any).records;
            } else if (Array.isArray(success)) {
                // 直接是数组的情况
                addressList = success;
            }

            // 强制更新store中的地址列表 - 直接替换数组
            nurseUser.value.nurseHomeAddrList = [...addressList];
            
            
            // 如果列表只有一项且不是默认地址，自动设置为默认地址
            if (addressList.length === 1) {
                const singleItem: any = addressList[0];
                const isDefault = singleItem.isDefault == 1 || singleItem.isDefault == '1' || singleItem.isDefault === true;
                
                if (!isDefault && singleItem.id) {
                    await autoSetDefaultAddress(singleItem.id);
                }
            }
        }
    } catch (err) {
        // 获取地址列表异常
    } finally {
        loading.value = false;
        hideLoading();
    }
}

// 强制刷新地址列表（清除缓存）
async function forceRefreshHomeAddrList() {
    // 清除当前数据
    nurseUser.value.nurseHomeAddrList = [];
    
    // 等待一下确保清除完成
    await new Promise(resolve => setTimeout(resolve, 100));
    
    // 重新获取数据
    await getHomeAddrList();
}

// 页面加载时获取地址列表
onMounted(() => {
    getHomeAddrList();
});

// 页面显示时强制刷新数据（从编辑页面返回时）
Taro.useDidShow(() => {
    forceRefreshHomeAddrList();
});

const clickItem = (_e: any, item: { id: string | undefined }) => {
    toAddr(item.id, true);
};

const editClick = (_e: any, item: { id: string | undefined }) => {
    toAddr(item.id, true);
};

const delClick = (_e: any, item: { id: string | undefined }) => {
    visible_delete.value = !visible_delete.value;
    _id.value = item.id || '';
};

const delClickSwipe = (_e: any, item: { id: string | undefined }) => {
    visible_delete.value = !visible_delete.value;
    _id.value = item.id || '';
};

// 自动设置默认地址（当列表只有一项时）
async function autoSetDefaultAddress(addressId: string) {
    try {
        const res: any = await setDefaultHomeAddr(addressId, nurseUser.value.id);
        
        if (!res.error) {
            
            // 等待一下再刷新数据
            setTimeout(async () => {
                await forceRefreshHomeAddrList();
            }, 300);
        }
    } catch (err) {
        // 自动设置默认地址异常
    }
}

// 设置默认地址
const setDefaultClick = async (_e: any, item: { id: string | undefined }) => {
    if (!item.id) return;

    showLoading({ title: '设置中...' });

    try {
        const res: any = await setDefaultHomeAddr(item.id, nurseUser.value.id);
        if (!res.error) {
            showToast({
                title: '设置成功',
                icon: 'success',
                duration: SUCCESS_MSG_DURATION
            });

            // 强制刷新地址列表
            setTimeout(async () => {
                await forceRefreshHomeAddrList();
            }, 300);
        } else {
            showToast({
                title: '设置失败',
                icon: 'error',
                duration: SUCCESS_MSG_DURATION
            });
        }
    } catch (err) {
        showToast({
            title: '设置失败',
            icon: 'error',
            duration: SUCCESS_MSG_DURATION
        });
    } finally {
        hideLoading();
    }
};

async function onDelete() {
    if (!_id.value) return;

    isDeleting.value = true; // 设置删除状态
    showLoading({ title: '正在删除...' });

    try {
        const { error } = await deleteHomeAddr(_id.value);

        if (!error) {
            showToast({
                title: '删除成功',
                icon: 'success',
                duration: SUCCESS_MSG_DURATION
            });

            // 强制刷新地址列表
            setTimeout(async () => {
                // 临时清除删除状态以允许刷新
                isDeleting.value = false;
                await forceRefreshHomeAddrList();
            }, 300);
        } else {
            showToast({
                title: '删除失败',
                icon: 'error',
                duration: SUCCESS_MSG_DURATION
            });
            isDeleting.value = false; // 删除失败时重置状态
        }
    } catch (err) {
        showToast({
            title: '删除失败',
            icon: 'error',
            duration: SUCCESS_MSG_DURATION
        });
        isDeleting.value = false; // 删除异常时重置状态
    } finally {
        hideLoading();
        visible_delete.value = false;
        _id.value = '';
    }
}

// 新增地址回调
const handleAddAddress = () => {
    toAddr('', true);
};

// 页面显示时刷新数据
defineExpose({
    getHomeAddrList,
    forceRefreshHomeAddrList
});
</script>
<template>
    <basic-layout>
        <!-- <custom-navbar title="我的地址" showLeft /> -->
        <view v-if="loading" class="text-center p-4">
            <view class="text-sm text-gray-500">加载中...</view>
        </view>
        <template v-else>
            <nut-empty v-if="!nurseUser.nurseHomeAddrList || nurseUser.nurseHomeAddrList.length == 0"
                description="暂无地址"></nut-empty>
            <view v-else class="w-375px text-primary b-rounded">
                <!-- 设置默认地址按钮 -->
                <view v-if="nurseUser.nurseHomeAddrList && nurseUser.nurseHomeAddrList.length > 0" class="mt-4">
                    <view v-for="item in nurseUser.nurseHomeAddrList" :key="item.id" class="mb-2 shadow-sm">
                        <view class="flex flex-col p-3 bg-gray-50 rounded">
                            <view class="w-full" @click="clickItem($event, item)">
                                <text class="text-sm font-medium">{{ item.name }} {{ item.phone }}</text>
                                <text v-if="item.isDefault == 1 || item.isDefault == '1' || item.isDefault === true" class="text-[18rpx] text-white ml-1 bg-green-700 p-[4rpx]">默认</text>
                            </view>
                            <view class="w-full text-xs text-gray-600 mt-1">{{ (item.areaName || '') + (item.address || '') }}</view>
                            <view class="w-full flex items-center justify-end gap-2 mt-2">
                                <!-- 编辑按钮 -->
                                <nut-button type="default" size="small" @click="editClick($event, item)">
                                    编辑
                                </nut-button>

                                <!-- 删除按钮 -->
                                <nut-button type="danger" size="small" @click="delClick($event, item)">
                                    删除
                                </nut-button>

                                <!-- 设置默认按钮 -->
                                
                                <nut-button v-if="item.isDefault == 1 || item.isDefault == '1' || item.isDefault === true" type="default" size="small" disabled>
                                    默认地址
                                </nut-button>
                                <nut-button v-else type="primary" size="small"
                                    @click="setDefaultClick($event, item)">
                                    设为默认
                                </nut-button>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="flex gap-2 m-t-2">
                <basic-button text="新增地址" class="flex-1" @on-click="handleAddAddress" />
                <!-- <basic-button text="刷新列表" class="flex-1" @on-click="forceRefreshHomeAddrList" /> -->
            </view>
        </template>
        <nut-dialog v-model:visible="visible_delete" title="提示" content="是否删除该地址？" @cancel="visible_delete = false"
            @ok="onDelete" />
    </basic-layout>
</template>
